package com.quan.web.controller.weixin;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quan.common.annotation.RequiresPermissions;
import com.quan.common.base.pojo.JSONResult;
import com.quan.common.core.support.BaseController;
import com.quan.common.utils.RandomUitl;
import com.quan.sdk.weixin.model.Menu;
import com.quan.sdk.weixin.tools.MenuTools;
import com.quan.weixin.rpc.api.WeixinMenuService;
import com.quan.weixin.rpc.model.WeixinMenu;

@RestController
@RequestMapping(value = "/api/weixin/menu")
public class WeixinMenuController extends BaseController {

	@Autowired
	private WeixinMenuService weixinMenuService;
	
	@RequiresPermissions(value="weixin:menu:add", description="添加微信菜单")
	@PostMapping(value = "/add")
	public Object add(@Valid @RequestBody WeixinMenu entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return JSONResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		entity.setEventKey(StringUtils.isNotEmpty(entity.getType()) ? entity.getType().toUpperCase() + "_" + RandomUitl.generateString(5).toUpperCase() : null);
		this.weixinMenuService.insertSelective(entity);

		return JSONResult.ok();
	}

	@RequiresPermissions(value="weixin:menu:delete", description="删除微信菜单")
	@GetMapping(value = "/delete/{id}")
	public Object delete(@PathVariable Integer id) {
		this.weixinMenuService.deleteById(Integer.valueOf(id.toString()));
		return JSONResult.ok();
	}

	@RequiresPermissions(value="weixin:menu:update", description="修改微信菜单")
	@PostMapping(value = "/update")
	public Object update(@Valid @RequestBody WeixinMenu entity, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
            return JSONResult.failure(bindingResult.getFieldError().getDefaultMessage()) ;
        }
		if(entity.getPid() == null) {
			entity.setPid(0);
		}
		this.weixinMenuService.update(entity);

		return JSONResult.ok();
	}

	@RequiresPermissions(value="weixin:menu:detail", description="查询微信菜单详情")
	@GetMapping(value = "/get/{id}")
	public Object list(@PathVariable Integer id) {
		return this.weixinMenuService.selectOneById(id);
	}
	
	@RequiresPermissions(value="weixin:menu:list", description="查询微信菜单")
	@GetMapping(value = "/list")
	public Object list(WeixinMenu entity, String orderby) {
		Integer pid = 0 ;
		if(entity.getPid() != null) {
			pid = entity.getPid();
		}
		return this.weixinMenuService.selectChildren(pid, orderby);
	}

	@RequiresPermissions(value="weixin:menu:tree", description="微信菜单树状")
	@GetMapping(value = "/tree")
	public Object tree(WeixinMenu entity, String orderby) {
		return this.weixinMenuService.tree(entity, orderby);
	}
	
	/**
	 * 获取节点的所有父节点
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/getParents")
	public Object getParents(Integer id) {
		return this.weixinMenuService.getParents(id);
	}
	
	/**
	 * 推送菜单到微信
	 * @return
	 */
	@RequiresPermissions(value="weixin:menu:pushMenuToWeiXin", description="微信菜单推送")
	@GetMapping(value="/pushMenuToWeiXin")
	public Object pushMenuToWeiXin(String orderby) {
		List<Menu> menus = new ArrayList<Menu>();

		List<WeixinMenu> root = this.weixinMenuService.selectRoot(orderby);
		for (WeixinMenu menu : root) {
			if(null != menu.getStatus() && menu.getStatus() == 1) {
				menus.add(recursiveWeixinMenu(menu, orderby));
			}
		}
		
		LinkedHashMap<String, List<Menu>> map = new LinkedHashMap<String, List<Menu>>();
		map.put("button", menus);
		
		JSONObject response = MenuTools.pushMenuToWeiXin(JSON.toJSONString(map)) ;
		if(response.getInteger("errcode") > 0) {
			logger.info("微信菜单推送失败：{}", response.toJSONString());
			return JSONResult.failure(response.getString("errmsg"));
		} else {
			logger.info("微信菜单推送成功：{}", response.toJSONString());
			return JSONResult.ok();
		}
	}
	
	private Menu recursiveWeixinMenu(WeixinMenu menu, String orderby) {
		Menu wxMenu = new Menu() ;
		wxMenu.setName(menu.getName());
		wxMenu.setKey(menu.getEventKey());
		wxMenu.setType(menu.getType());
		wxMenu.setUrl(menu.getUrl());
		wxMenu.setAppid(menu.getAppid());
		wxMenu.setPagepath(menu.getPagepath());
		wxMenu.setMedia_id(menu.getMediaId());
		
		List<WeixinMenu> childs = this.weixinMenuService.selectChildren(menu.getId(), orderby);
		if (null != childs && childs.size() > 0) {
			List<Menu> sub_menus = new ArrayList<Menu>() ;
			for (WeixinMenu m : childs) {
				if(m.getStatus() == 1) {
					Menu wxm = new Menu() ;
					wxm.setName(m.getName());
					wxm.setKey(m.getEventKey());
					wxm.setType(m.getType());
					wxm.setUrl(m.getUrl());
					wxm.setAppid(menu.getAppid());
					wxm.setPagepath(menu.getPagepath());
					wxm.setMedia_id(menu.getMediaId());
					
					sub_menus.add(recursiveWeixinMenu(m, orderby));
				}
				
			}
			wxMenu.setSub_button(sub_menus);
		}
		return wxMenu;
	}
}
